<?php
/**
 * @Description 
 * @Sonkwl Xiong
 * @Date 2023/09/19 13:33:55
 * @GET 
 * 
 * @POST 
 * 
 * @Response 
 *  
 */
namespace Sonkwl\UsePHP;

use \Sonkwl\UsePHP\jsoner;

//将设计文件转换成项目基本配置(DB,interface,document)
class designToConfig{
    private static $dictionary=array();//数据字典数组
    private static $interface=array();//接口数组
    private static $database=array();//数据库数组
    //读取设计文件
    public static function ReadDir($fileArr){
        //验证$filearr是否有效
        if(!is_array($fileArr)){
            jsoner::Response(array("res"=>"NG","message"=>"ReadDir必须是数据"));
        }
        if(!isset($fileArr["dictionary"]) || !isset($fileArr["interface"]) || !isset($fileArr["database"])){
            jsoner::Response(array("res"=>"NG","message"=>"ReadDir必须定义dictionary，interface，database的目录"));
        }
        self::$dictionary=self::ReadDirToArray($fileArr["dictionary"]);
        self::$interface=self::ReadDirToArray($fileArr["interface"]);
        self::$database=self::ReadDirToArray($fileArr["database"]);
        return __CLASS__;
    }

    //读取文件夹所有文件，返回array
    public static function ReadDirToArray($dir){
        if(!is_dir($dir)){
            jsoner::Response(array("res"=>"NG","message"=>"ReadDir定义的".$dir."目录不存在"));
        }
        $dataArray=array();
        foreach(scandir($dir) as $file){
            if($file=="." || $file==".."){
                continue;
            }
            if(!strstr($file,".json")){
                continue;
            }
            $json=file_get_contents($dir."/".$file);
            $json=json_decode($json,true);
            $dataArray=array_merge($dataArray,$json);
        }
        return $dataArray;
    }

    //运行配置
    public static function Run($config){
        foreach($config as $key => $value){
            call_user_func("self::Run_".$value);
        }
    }

    //创建sql语句
    public static function CreateSql(){
        $sql="";
        foreach (self::$database as $key => $tbl) {
            $sql.="drop table if exists ".$tbl["table"].";\n";
            $sql.="create table ".$tbl["table"]."(\n";
            foreach ($tbl["column"] as $key2 => $column) {
                $sql.=$column;
                if(!isset(self::$dictionary[$column])){
                    jsoner::Response(array("res"=>"NG","message"=>"数据字典中不存在".$column));
                }
                if(self::$dictionary[$column]["type"]=="string"){
                    $sql.=" varchar(".self::$dictionary[$column]["max"]."),";
                }else{
                    $sql.=" ".self::$dictionary[$column]["type"].",";
                }
                $sql=trim($sql,",")."\n";
            }
            $sql.=")charset=utf8;\n";
        }
        return $sql;
    }
    //生成database
    public static function Run_database(){
        $sql=self::CreateSql();
        echo $sql;
    }
    //生成databasefile
    public static function Run_databasefile(){
        $sql=self::CreateSql();
        file_put_contents("database-dev.sql",$sql);
    }
    //生成control
    public static function Run_control(){
        if(!is_dir("control")){
            mkdir("control",0777);
        }
        if(!is_dir("control/get")){
            mkdir("control/get",0777);
        }
        if(!is_dir("control/post")){
            mkdir("control/post",0777);
        }
        if(!is_dir("control/validate")){
            mkdir("control/validate",0777);
        }
        self::CreateIndexFile();
        self::CreateValidateFile();
        echo "<hr>Succuss:生成control";
    }
    //生成index.php
    public static function CreateIndexFile(){
        if(is_file("control/index.php")){
            return;
        }
        $file="<?php\n";
        $file.="//项目入口文件\n";
        $file.="include \$_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';\n";
        $file.="use \Sonkwl\UsePHP\autoroute;\n";
        $file.="use \Sonkwl\UsePHP\jwt;\n";
        $file.="use \Sonkwl\UsePHP\mysqler;\n";
        $file.="use \Sonkwl\UsePHP\autocontrol;\n\n";
        $file.="mysqler::SetPDO('".mysqler::GetPDOString()."');\n";
        $file.="mysqler::SetUser('".mysqler::GetUser()."');\n";
        $file.="mysqler::SetPWD('".mysqler::GetPWD()."');\n\n";
        $file.="jwt::SetVersion('V1');\n";
        $file.="jwt::SetKeyInt('1');\n";
        $file.="jwt::SetKeyStr('WHSS');\n";
        $file.="jwt::SetExp(strtotime(\"+8 hours\",time()));\n\n";
        $file.="autoroute::ValidateRequest();\n";
        $file.="autoroute::Run();\n";
        $file.="?>\n";
        file_put_contents("control/index.php",$file);
    }
    //生成CreateValidateFile文件
    public static function CreateValidateFile(){
        foreach (self::$interface as $key => $inter) {
            //生成响应文件
            if(!is_file("control/".strtolower($inter["method"])."/".$inter["url"].".php")){
                $file="<?php\n";
                $file.="//@DESC ".$inter["desc"]."\n";
                $file.="//@INPUT ".implode(",",$inter["request"])."\n";
                $file.="//@OUTPUT ".implode(",",$inter["response"])."\n";
                $file.="?>\n";
                file_put_contents("control/".strtolower($inter["method"])."/".$inter["url"].".php",$file);
            }
            //生成验证文件
            $file="<?php\n";
            $file.="use \Sonkwl\UsePHP\jsoner;\n";
            //查询数据字典验证
            foreach ($inter["request"] as $column => $number) {
                $inputColumn="\$_".strtoupper($inter["method"])."[\"".$column."\"]";
                if(!isset(self::$dictionary[$column])){
                    jsoner::Response(array("res"=>"NG","message"=>"数据字典中没有".$column));
                }
                $numberRange=explode(":",$number);
                if($numberRange[0]==1){
                    $file.="if(!isset({$inputColumn})){\n";
                    $file.="    jsoner::Response(array(\"res\"=>\"NG\",\"message\"=>\"{$column}没有定义\"));\n";
                    $file.="}\n";
                    $min=self::$dictionary[$column]["min"];
                    $max=self::$dictionary[$column]["max"];
                    $file.="if(strlen({$inputColumn})<{$min} || strlen({$inputColumn})>{$max}){\n";
                    $file.="    jsoner::Response(array(\"res\"=>\"NG\",\"message\"=>\"{$column}字数必须在{$min} ~{$max}之间\"));\n";
                    $file.="}\n";

                    //中文正则处理
                    $regex=str_replace("\u4e00-\u9fa5","\x{4e00}-\x{9fa5}",self::$dictionary[$column]["regex"]);
                    if($regex!=""){
                        $file.="if(!preg_match(\"{$regex}u\",{$inputColumn})){\n";
                        $file.="    jsoner::Response(array(\"res\"=>\"NG\",\"message\"=>\"{$column}的格式不符合规定\"));\n";
                        $file.="}\n";
                    }
                    continue;
                }

                

                
            }

            $file.="?>\n";
            file_put_contents("control/validate/".strtolower($inter["method"])."-".$inter["url"].".php",$file);
        }
    }
    //生成document
    public static function Run_document(){
        if(!is_dir("document")){
            mkdir("document",0777);
        }
        echo '<hr>Succuss:生成document';
    }
}
?>